﻿// PBag.cpp: CPBag 的实现

#include "pch.h"
#include "PBag.h"


// CPBag

HRESULT __stdcall CPBag::Read(LPCOLESTR pszPropName, VARIANT* pVar, IErrorLog* pErrorLog)
{
    DWORD dwBytes;
    SetFilePointer(m_hFile, sizeof(UINT), NULL, FILE_BEGIN);
    UINT i;
    LONG Get = 0;
    for (i = 0; i < cCount; i++)
    {
        ReadFile(m_hFile, &Data, sizeof(DATATYPE), &dwBytes, NULL);
        if (!_tcscmp(pszPropName, Data.szName))
        {
            pVar->vt = VT_BSTR;
            pVar->bstrVal = SysAllocString(Data.szString);
            Get = 1;
            break;
        }
    }
    if (Get == 0)
        return E_FAIL;
    return S_OK;
}

HRESULT __stdcall CPBag::Write(LPCOLESTR pszPropName, VARIANT* pVar)
{
    DWORD dwBytes;
    SetFilePointer(m_hFile, sizeof(UINT), NULL, FILE_BEGIN);
    UINT i;
    LONG Get = 0;
    for (i = 0; i < cCount; i++)
    {
        ReadFile(m_hFile, &Data, sizeof(DATATYPE), &dwBytes, NULL);
        if (!_tcscmp(pszPropName, Data.szName))
        {
            RtlCopyMemory(Data.szString, pVar->bstrVal, _tcslen(pVar->bstrVal) * 2 + 2);
            SetFilePointer(m_hFile, -(long)sizeof(DATATYPE), NULL, FILE_CURRENT);
            WriteFile(m_hFile, &Data, sizeof(DATATYPE), &dwBytes, NULL);
            Get = 1;
            break;
        }
    }
    if (Get == 0)
    {
        RtlCopyMemory(Data.szString, pVar->bstrVal, _tcslen(pVar->bstrVal) * 2 + 2);
        RtlCopyMemory(Data.szName, pszPropName, _tcslen(pszPropName) * 2 + 2);
        WriteFile(m_hFile, &Data, sizeof(DATATYPE), &dwBytes, NULL);
        cCount++;
        SetFilePointer(m_hFile, 0, NULL, FILE_BEGIN);
        WriteFile(m_hFile, &cCount, sizeof(UINT), &dwBytes, NULL);
        return S_OK;
    }
    return S_OK;
}
